﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Clancy.Common
{
    public static class BitmapExtensions
    {
        public static Bitmap ToBitmap(this byte[] byteData)
        {
            if (byteData == null)
                return null;

            using (MemoryStream ms = new MemoryStream(byteData))
            {
                return Image.FromStream(ms) as Bitmap;
            }
        }

        public static BitmapSource ToBitmapSource(this byte[] byteData)
        {
            if ((byteData == null) || (byteData.Length == 0))
                return null;

            using (MemoryStream ms = new MemoryStream(byteData))
            {
                JpegBitmapDecoder decoder = new JpegBitmapDecoder(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
                BitmapSource bitmapSource = decoder.Frames[0];
                bitmapSource.Freeze();
                return bitmapSource;
            }
        }

        public static ImageSource ToImageSource(this Bitmap bmp)
        {
            if (bmp == null)
                return null;

            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                        bmp.GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        BitmapSizeOptions.FromEmptyOptions());
        }

        public static byte[] ToJpegByteArray(this Bitmap bitmap)
        {
            if (bitmap == null)
                return null;

            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Jpeg);
                return ms.ToArray();
            }
        }

        public static byte[] ToJpegByteArray(this BitmapSource bitmapSource)
        {
            if (bitmapSource == null)
                return null;

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            encoder.QualityLevel = 80;
            byte[] byteWurscht;
            using (MemoryStream stream = new MemoryStream())
            {
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                encoder.Save(stream);
                byteWurscht = stream.ToArray();
                stream.Close();
            }
            return byteWurscht;
        }
    }
}